package com.kuaiyin.executor;

import com.fasterxml.jackson.databind.JsonNode;
import com.kuaiyin.entity.Request;
import com.kuaiyin.entity.TestCase;
import com.kuaiyin.mapper.RequestMapper;
import com.kuaiyin.mapper.TestCaseMapper;
import com.kuaiyin.utils.RedisUtils;

import java.util.Map;

public class TestCaseExecutor extends AbstractRequestExecutor {

    private final TestCaseMapper testCaseMapper;
    private final RequestMapper requestMapper;
    private final Long testCaseId;

    public TestCaseExecutor(TestCaseMapper testCaseMapper, RequestMapper requestMapper, RedisUtils redisUtils, Long testCaseId) {
        super(redisUtils);
        this.testCaseMapper = testCaseMapper;
        this.requestMapper = requestMapper;
        this.testCaseId = testCaseId;
    }

    @Override
    protected Request getRequest(Long id) {
        TestCase testCase = testCaseMapper.selectById(id);
        return requestMapper.selectById(testCase.getRequestId());
    }

    @Override
    protected String getEnvironmentType(Long id) {
        return testCaseMapper.selectById(id).getEnvironmentType();
    }

    @Override
    protected Map<String, Object> getAssertions(Long id) {
        return testCaseMapper.selectById(id).getAssertions();
    }

    @Override
    protected void updateExecutionStatus(Long id, String status) {
        TestCase testCase = testCaseMapper.selectById(id);
        testCase.setExecStatus(status);
        testCaseMapper.updateById(testCase);
    }

    @Override
    protected void saveToRedis(Long id, String url, Map<String, Object> body, Map<String, Object> headers, JsonNode response, Map<String, Object> assertions, String method) {
        String redisKey = String.format("testCase_id_%d", id);
        redisUtils.saveToHash(
                redisKey,
                86400L,
                "requestUrl", url,
                "requestBody", body,
                "response", response,
                "requestHeader", headers,
                "assertions", assertions,
                "method", method
        );
    }
}
